package com.tjsinfo.tjsoa.messageImportant.action;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.tjsinfo.tjsoa.Dao.IJDBCDao;
import com.tjsinfo.tjsoa.common.DealString;
import com.tjsinfo.tjsoa.common.FileManage;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.message.vo.TjsMessage;
import com.tjsinfo.tjsoa.messageImportant.bo.IMessageImportantFileUploadBo;
import com.tjsinfo.tjsoa.messageImportant.bo.IMessageImportantInceptBo;
import com.tjsinfo.tjsoa.messageImportant.bo.IMessageImportantMainBo;
import com.tjsinfo.tjsoa.messageImportant.vo.MessageImportantFileUpload;
import com.tjsinfo.tjsoa.messageImportant.vo.MessageImportantIncept;
import com.tjsinfo.tjsoa.messageImportant.vo.MessageImportantMain;
import com.tjsinfo.tjsoa.system.bo.ISystemUserBo;
import com.tjsinfo.tjsoa.system.vo.Files;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;
import com.tjsinfo.tjsoa.system.vo.User;


public class InsertMessageAction extends Action {
	private IMessageImportantMainBo importantMainBo;
	private ISystemUserBo tjsUserBo;
	private IMessageImportantInceptBo importantInceptBo;
	private IMessageImportantFileUploadBo importantFileUploadBo;
	private IJDBCDao jdbcdao;

	public void setImportantFileUploadBo(
			IMessageImportantFileUploadBo importantFileUploadBo) {
		this.importantFileUploadBo = importantFileUploadBo;
	}

	public IMessageImportantInceptBo getImportantInceptBo() {
		return importantInceptBo;
	}

	public void setImportantInceptBo(IMessageImportantInceptBo importantInceptBo) {
		this.importantInceptBo = importantInceptBo;
	}

	public ISystemUserBo getTjsUserBo() {
		return tjsUserBo;
	}

	public void setTjsUserBo(ISystemUserBo tjsUserBo) {
		this.tjsUserBo = tjsUserBo;
	}

	public IMessageImportantMainBo getImportantMainBo() {
		return importantMainBo;
	}

	public void setImportantMainBo(IMessageImportantMainBo importantMainBo) {
		this.importantMainBo = importantMainBo;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		Configuration configuration;
		String fromFilePath = "";
		try {
			configuration = new PropertiesConfiguration("com/tjsinfo/tjsoa/system/properties/systemResource.properties");
			fromFilePath = configuration.getString("system.uploadFile.tempFilePath");
		} catch (ConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String nowSQL = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty("nowSQL");
		String toFilePath = ToolKit.getProperties("com/tjsinfo/tjsoa/messageImportant/properties/systemResource.properties", this).getProperty(nowSQL+".fileurl");
		List<Files> fileList=DealString.fileCopyTofile(request, fromFilePath, toFilePath);
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String jieshourenid = request.getParameter("jieshourenid");
		String[] jieshourens = jieshourenid.split("@");

		String sendTime = request.getParameter("sendTime");
		
		String info = request.getParameter("info");
		if (info != null && !"".equals(info)) {
			info = info.replace("\r\n", "<br/>");
			info=info.replace("\"","“");
			info=info.replace("\'","‘");
		}
		TSystemUser tjsUser = tjsUserBo.findByIdSystemUser(user.getUser_id());
		MessageImportantMain main = new MessageImportantMain();
		// 插入时间
		Date date = new Date();
		try {
			main.setDatetime(sdf.parse(sdf.format(date)));
			if(sendTime!=null && !"".equals(sendTime)){
				main.setSendtime(sdf.parse(sendTime));
			}else {
				main.setSendtime(sdf.parse(sdf.format(date)));
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		main.setSendUserId(tjsUser.getUserId());
		main.setSendUsername(tjsUser.getUserName());
		main.setInfo(info);
		main.setSendSql(nowSQL);
		main.setState(0);
		if(fileList.size()>0){
			main.setFileUpload("yes");
		}
		String id = importantMainBo.save(main);
		main.setId(id);
		
		//提交上传附件
		for (Files files : fileList) {
			MessageImportantFileUpload fileUpload = new MessageImportantFileUpload();
			fileUpload.setUuid(UUID.randomUUID().toString().replace("-", ""));
			fileUpload.setMainId(main.getId());
			fileUpload.setFilePath(files.getToFilePath());
			fileUpload.setNewFileName(files.getNewFileName());
			fileUpload.setOldFileName(files.getOldFileName());
			
			importantFileUploadBo.save(fileUpload);
		}

		HashMap<String, String> map = new HashMap<String, String>();
		HashMap<String, List<String>> sqlMap = new HashMap<String, List<String>>();
		List<String> nowList = new ArrayList<String>();//发送当前数据库的用户
		HashMap<String, String> otherMap = new HashMap<String, String>();//发送其他数据库的用户
		String other = "";//发送其他数据库的用户，用户名逗号分隔
		List<String> list1 = new ArrayList<String>();
		
		/**
	     * 循环主送，区分当前系统数据库nowList，并将其他数据库的人员分类存储sqlMap
	     */
		for (int i = 0; i < jieshourens.length; i++) {
			if(jieshourens[i]!= null && !"".equals(jieshourens[i]))//主送
			{
				String[] zhusongarray =  jieshourens[i].split(",");
				if (map.get(zhusongarray[1])==null) {
					map.put(zhusongarray[1], zhusongarray[0]);
					
					if (nowSQL.equals(zhusongarray[2])) {
						nowList.add(zhusongarray[0]+","+zhusongarray[1]);
					}else {
						other += zhusongarray[1]+","+zhusongarray[2]+"@";
						otherMap.put(zhusongarray[1], zhusongarray[0]+","+zhusongarray[2]);
						if (sqlMap.get(zhusongarray[2])==null) {
							list1 = new ArrayList<String>();
						}else {
							list1 = sqlMap.get(zhusongarray[2]);
						}
						list1.add(zhusongarray[0]+","+zhusongarray[1]);
						sqlMap.put(zhusongarray[2], list1);
					}
				}else {
					continue;
				}
			}
		}
		
		//当前系统人员录入
		for (Iterator iterator = nowList.iterator(); iterator.hasNext();) {
			String str = (String) iterator.next();
			String userid = str.split(",")[0];
			String username = str.split(",")[1];
			
			MessageImportantIncept incept = new MessageImportantIncept();
			incept.setMessageImportantMain(main);
			incept.setState(0);
			incept.setReceiveUserId(Integer.parseInt(userid));
			incept.setReceiveUsername(username);
			incept.setSendSql(nowSQL);
			importantInceptBo.save(incept);
		}
		//当前系统人员录入其他系统的接收人
		String[] s = other.split("@");
		for (int i = 0; i < s.length; i++) {
			if (s[i]!=null && !"".equals(s[i])) {
				MessageImportantIncept incept = new MessageImportantIncept();
				incept.setMessageImportantMain(main);
				incept.setState(0);
				incept.setReceiveUsername(s[i].split(",")[0]);
				incept.setSendSql(s[i].split(",")[1]);
				importantInceptBo.save(incept);
			}
		}
		
		//其他系统接收人，循环有几个数据库
		Iterator iter = sqlMap.entrySet().iterator(); 
		while (iter.hasNext()) {
		    Map.Entry entry = (Map.Entry) iter.next(); 
		    String mssqlNum= (String) entry.getKey();//单个的其他数据库
		    String mssql = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty(mssqlNum);
		    List<String> val = (List<String>) entry.getValue();//其他数据库中的接收人 
		    
		    /**
		     * 开始，向数据库插入email主表发送信息，附件信息
		     */
			String uuidMessage = main.getId();
			String file = main.getFileUpload();
			if (main.getFileUpload()==null) {
				file = "";
			}
			String sql = "insert into "+mssql+".dbo.t_messageImportant_main(id,sendUser_id,send_username,info,datetime,fileUpload,send_sql,state)" +
					" values('"+uuidMessage+"',"+SessionUser.getUserId(request)+",'"+SessionUser.getUser(request).getUsername()+"','"+info+"','"+sdf.format(new Date())+"','"+file+"','"+nowSQL+"',1);";

			if(sendTime!=null && !"".equals(sendTime)){
				try {
					sql = "insert into "+mssql+".dbo.t_messageImportant_main(id,sendUser_id,send_username,info,datetime,fileUpload,sendTime,send_sql,state)" +
					" values('"+uuidMessage+"',"+SessionUser.getUserId(request)+",'"+SessionUser.getUser(request).getUsername()+"','"+info+"','"+sdf.format(new Date())+"','"+file+"','"+sdf.format(sdf.parse(sendTime))+"','"+nowSQL+"',1);";
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			jdbcdao.executeUpdate(sql);
			
			//mail数据表插入附件数据
			String toPath = ToolKit.getProperties("com/tjsinfo/tjsoa/messageImportant/properties/systemResource.properties", this).getProperty(mssqlNum+".fileurl");
			for (Files files : fileList) {
				MessageImportantFileUpload fileUpload = new MessageImportantFileUpload();
				fileUpload.setUuid(UUID.randomUUID().toString().replace("-", ""));
				fileUpload.setMainId(main.getId());
				fileUpload.setFilePath(files.getToFilePath());
				fileUpload.setNewFileName(files.getNewFileName());
				fileUpload.setOldFileName(files.getOldFileName());
				
				String fuuid = UUID.randomUUID().toString().replace("-", "");
				sql = "insert into "+mssql+".dbo.t_messageImportant_fileUpload(uuid,newFileName,oldFileName,main_id)" +
						" values('"+fuuid+"','"+files.getNewFileName()+"','"+files.getOldFileName()+"','"+uuidMessage+"');";
				jdbcdao.executeUpdate(sql);
				FileManage.moveFile(toFilePath+files.getNewFileName(), toPath+files.getNewFileName());
			}
			/**
		     * 结束
		     */
			
			/**
		     * 开始，向发送的其他数据库，插入循环到当前系统数据库的接收人员信息
		     */
			for (Iterator iterator = nowList.iterator(); iterator.hasNext();) {
				String str = (String) iterator.next();
				String username = str.split(",")[1];
				String uuid = UUID.randomUUID().toString().replace("-", "");
				
				String sql1 = "insert into "+mssql+".dbo.t_messageImportant_incept(id,main_id,receiveUser_id,receive_username,state,send_sql)" +
				" values('"+uuid+"','"+uuidMessage+"',null,'"+username+"',0,'"+nowSQL+"');";
				jdbcdao.executeUpdate(sql1);
			}
			/**
		     * 结束
		     */
			
			/**
		     * 开始，向发送的其他数据库，插入其他数据库的接收人员信息
		     */
			Iterator iter1 = otherMap.entrySet().iterator(); 
			while (iter1.hasNext()) {
			    Map.Entry entry1 = (Map.Entry) iter1.next(); 
			    String username = (String) entry1.getKey();
			    String str1 = (String) entry1.getValue();
			    String userid = str1.split(",")[0];
			    String msql = str1.split(",")[1];
			    boolean bl = true;
			    for (Iterator iterator = val.iterator(); iterator.hasNext();) {
					String str = (String) iterator.next();
					if (username.equals(str.split(",")[1])) {//当前循环到的其他数据库系统用户
						String uuid = UUID.randomUUID().toString().replace("-", "");
						String sql1 = "insert into "+mssql+".dbo.t_messageImportant_incept(id,main_id,receiveUser_id,receive_username,state,send_sql)" +
						" values('"+uuid+"','"+uuidMessage+"',"+userid+",'"+username+"',0,'"+msql+"');";
						jdbcdao.executeUpdate(sql1);
						
						bl = false;
						continue;
					}
				}
			    if (bl) {//其他数据库的系统用户
			    	String uuid = UUID.randomUUID().toString().replace("-", "");
					String sql1 = "insert into "+mssql+".dbo.t_messageImportant_incept(id,main_id,receiveUser_id,receive_username,state,send_sql)" +
					" values('"+uuid+"','"+uuidMessage+"',null,'"+username+"',0,'"+msql+"');";
					jdbcdao.executeUpdate(sql1);
				}
			}
			/**
		     *结束，向发送的其他数据库，插入其他数据库的接收人员信息
		     */
		} 
		jdbcdao.closeStmt();
		Connection con = jdbcdao.getConn();
		try {
			if (!con.isClosed()) {
				jdbcdao.closeConn();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		/**
	     * 发送提醒
	     */
		map = new HashMap<String, String>();
		for (int i = 0; i < jieshourens.length; i++) {
			if(jieshourens[i]!= null && !"".equals(jieshourens[i]))//主送
			{
				String[] zhusongarray =  jieshourens[i].split(",");
				if (map.get(zhusongarray[1])==null) {
					map.put(zhusongarray[1], zhusongarray[0]);
					
					TjsMessage message1 = new TjsMessage();
					message1.setSendusername(SessionUser.getUser(request).getUsername());
					message1.setRecusername(zhusongarray[1]);
					message1.setValue(SessionUser.getUser(request).getUsername()+"向您发送重要信息，请登录TJSOA进行查阅。");
					//TjsMessage.send(message1);
				}else {
					continue;
				}
			}
		}
		
		request.setAttribute("linkurl", "tjsinfo/tjsoa/messageImportant/loginSendMain.do");
		request.setAttribute("message", "messageimportant.message.save");
		return mapping.findForward("success");
	}

	public void setJdbcdao(IJDBCDao jdbcdao) {
		this.jdbcdao = jdbcdao;
	}
}
